﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using SaunaServer.Model.Network;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using SaunaServer.Controller.Communication;
using MySql.Data.MySqlClient;
using SaunaServer.View;

namespace SaunaServer.View
{
    public partial class CommunicationServerForm : Form
    {
        // Private variables
        ICommunicationManager communicationManager;

        private const int LIST_MAX = 30;
        private const string COLUMN_HEADER_RANK = "Rank";
        private const string COLUMN_HEADER_FILE_NAME = "File Name";
        private const string COLUMN_HEADER_COUNT = "Count";
        private const int COLUMN_WIDTH_RANK = 58;
        private const int COLUMN_WIDTH_FILE_NAME = 150;
        private const int COLUMN_WIDTH_COUNT = 60;
        private const int FORM_SIZE_EXPAND_X = 1234;
        private const int FORM_SIZE_EXPAND_Y = 795;
        private const int FORM_SIZE_CONTRACT_X = 493;
        private const int FORM_SIZE_CONTRACT_Y = 463;

        /// <summary>
        /// Sauna Communicate Server form constructor
        /// </summary>
        public CommunicationServerForm()
        {            
            InitializeComponent();

            // Create Communication Manager
            communicationManager = new CommunicationManager(this);

            ShowPopularDownloadFileRanking();

            // Set contracted form size
            this.Size = new Size(FORM_SIZE_CONTRACT_X, FORM_SIZE_CONTRACT_Y);
        }

        /// <summary>
        /// Server start button event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void ButtonStartServer_Click(object sender, EventArgs e)
        {
            // Disable Start Button
            ButtonStartServer.Enabled = false;

            // Start Sauna Server
            communicationManager.StartCommunication();

        }

        /// <summary>
        /// Refresh button event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void ButtonRefresh_Click(object sender, EventArgs e)
        {
            // Redraw controls
            ShowPopularDownloadFileRanking();

        }

        /// <summary>
        /// Start server menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void startServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ButtonStartServer.Enabled == true)
            {
                // Disable Start Button
                ButtonStartServer.Enabled = false;

                // Start Sauna Server
                communicationManager.StartCommunication();
            }
        }

        /// <summary>
        /// End Server menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void endServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ButtonStartServer.Enabled == false)
            {
                // End Previous Communication
                communicationManager.EndCommunication();
                communicationManager = null;

                // Recreate Communication Manager
                communicationManager = new CommunicationManager(this);

                // Enable Start Button
                ButtonStartServer.Enabled = true;
            }
        }

        /// <summary>
        /// Option menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void optionToolStripMenuItem_Click(object sender, EventArgs e)
        {

            NetworkSetting networkSetting = communicationManager.ReadConfigFile();
            if (networkSetting == null)
            {
                // When Sauna configuration file does not exist, create network setting with default values
                networkSetting = new NetworkSetting();
            }

            ClientOptionForm clientOptionForm = new ClientOptionForm(networkSetting);

            if (clientOptionForm.ShowDialog() == DialogResult.OK)
            {
                //networkSetting.Copy(clientOptionForm.networkSetting);

                // End Previous Communication
                communicationManager.EndCommunication();
                communicationManager = null;

                // Recreate Communication Manager
                communicationManager = new CommunicationManager(this);

                // Enable Start Button
                ButtonStartServer.Enabled = true;
            }

        }

        /// <summary>
        /// Expand menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void expandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Set expanded form size
            this.Size = new Size(FORM_SIZE_EXPAND_X, FORM_SIZE_EXPAND_Y);
        }

        /// <summary>
        /// Contract menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void contractToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Set contracted form size
            this.Size = new Size(FORM_SIZE_CONTRACT_X, FORM_SIZE_CONTRACT_Y);
        }

        /// <summary>
        /// Show popular download file ranking list
        /// </summary>
        public void ShowPopularDownloadFileRanking()
        {

            string[,] popularFileRankingList;

            popularFileRankingList = communicationManager.GetPopularFileRanking();
            listViewPopularFileRanking.Items.Clear();
            listViewPopularFileRanking.Columns.Clear();

            ColumnHeader columnHeader1 = new ColumnHeader();
            columnHeader1.Text = COLUMN_HEADER_RANK;
            columnHeader1.Width = COLUMN_WIDTH_RANK;
            columnHeader1.TextAlign = HorizontalAlignment.Left;
            listViewPopularFileRanking.Columns.Add(columnHeader1);

            ColumnHeader columnHeader2 = new ColumnHeader();
            columnHeader2.Text = COLUMN_HEADER_FILE_NAME;
            columnHeader2.Width = COLUMN_WIDTH_FILE_NAME;
            columnHeader2.TextAlign = HorizontalAlignment.Left;
            listViewPopularFileRanking.Columns.Add(columnHeader2);

            ColumnHeader columnHeader3 = new ColumnHeader();
            columnHeader3.Text = COLUMN_HEADER_COUNT;
            columnHeader3.Width = COLUMN_WIDTH_COUNT;
            columnHeader3.TextAlign = HorizontalAlignment.Left;
            listViewPopularFileRanking.Columns.Add(columnHeader3);

            for (int i = 0; i < LIST_MAX; i++)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = popularFileRankingList[i, 0];
                listViewItem.SubItems.Add(popularFileRankingList[i, 1]);
                listViewItem.SubItems.Add(popularFileRankingList[i, 2]);
                listViewPopularFileRanking.Items.Add(listViewItem);
            }
        }

        /// <summary>
        /// Inintialize controls with dataset
        /// </summary>
        private void CommunicationServerForm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'saunadDataSet.userdownloadcount' table. You can move, or remove it, as needed.
            this.userdownloadcountTableAdapter.Fill(this.saunadDataSet.userdownloadcount);
            // TODO: This line of code loads data into the 'saunadDataSet.downloadranking' table. You can move, or remove it, as needed.
            this.downloadrankingTableAdapter.Fill(this.saunadDataSet.downloadranking);
            // TODO: This line of code loads data into the 'saunadDataSet.select_downloadrank' table. You can move, or remove it, as needed.
            this.select_downloadrankTableAdapter.Fill(this.saunadDataSet.select_downloadrank);
            // TODO: This line of code loads data into the 'saunadDataSet.downloadlog' table. You can move, or remove it, as needed.
            this.downloadlogTableAdapter.Fill(this.saunadDataSet.downloadlog);
        }

        private void downloadrankingBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Write a message to monitor control
        /// </summary>
        /// <param name="message">display message</param>
        public void WriteMonitorMessage(String message)
        {
            if (textBoxMonitor.InvokeRequired == true)
            {
                textBoxMonitor.Invoke(new MethodInvoker(delegate
                {
                    textBoxMonitor.Text += message + System.Environment.NewLine;
                }));
            }
            else
            {
                textBoxMonitor.Text += message + System.Environment.NewLine;
            }
            Console.WriteLine(message);
        }

    }

}
